package com.wmmt.flutter_tencent_location

import android.content.Context
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FlutterTencentLocationPlugin */
class FlutterTencentLocationPlugin : FlutterPlugin, MethodCallHandler, TencentLocationListener {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private lateinit var manager: TencentLocationManager
    private var mContext: Context? = null
    private lateinit var tencentLocationRequest: TencentLocationRequest
    private var resultList: ArrayList<Result> = arrayListOf()

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_tencent_location")
        channel.setMethodCallHandler(this)
        mContext = flutterPluginBinding.applicationContext
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        println("Tencent:onMethodCall:${call.method}")
        when (call.method) {
            "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
            "setUserAgreePrivacy" -> TencentLocationManager.setUserAgreePrivacy(
                true
            )

            "flutter_tenc_map_init" -> initMap(result)
            "stopLocation" -> stopLocation(result)
            "flutter_tenc_map_getLocation" -> getLocation(call, result)
            else -> result.notImplemented()
        }
    }

    private fun getLocation(call: MethodCall, result: Result) {
        var interval: Long = 10000
        if (call.hasArgument("interval")) {
            interval = ((call.arguments as HashMap<String, Any>)["interval"] as Double).toLong();
        }
        if (resultList.size <= 0) {
            tencentLocationRequest.interval = interval;
            val error = manager.requestLocationUpdates(
                tencentLocationRequest, this
            )
            println("TencentMap:code:$error")
            if (error != 0) {
                resultList.clear()
                result.success("error")
            }
        }
        //获取一次定位
        this.resultList.add(result)
    }

    private fun stopLocation(result: Result) {
        resultList.clear()
        android.os.Handler().postDelayed({
            manager.removeUpdates(this)
        }, 100)
        result.success(true)
    }

    private fun initMap(result: Result) {
        manager = TencentLocationManager.getInstance(mContext)
        tencentLocationRequest = TencentLocationRequest.create()
        tencentLocationRequest.isAllowGPS = true
        tencentLocationRequest.isIndoorLocationMode = true
        tencentLocationRequest.locMode = TencentLocationRequest.HIGH_ACCURACY_MODE
        tencentLocationRequest.isGpsFirst = true
        tencentLocationRequest.setGpsFirstTimeOut(5000)
        result.success("Tencent Map初始化成功")
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onLocationChanged(location: TencentLocation?, error: Int, p2: String?) {
        println("Tencent:onLocationChanged:${location?.address}")
        if (error == 0) {
            val map = HashMap<String, Any?>();
            map.put("name", location?.name)
            map.put("latitude", location?.latitude)
            map.put("longitude", location?.longitude)
            map.put("address", location?.address)
            map.put("city", location?.city)
            map.put("province", location?.province)
            map.put("area", location?.district)
            map.put("cityCode", location?.cityCode)
            map.put("code", 200)
            for (result in resultList.iterator()) {
                result.success(map)
            }
            resultList.clear();
            channel.invokeMethod("flutter_tenc_map_backLocation", map)
        } else {
            val map = HashMap<String, Any>();
            var code = 4
            when (error) {
                1 -> {
                    code = 2
                }

                2 -> {
                    code = 1
                }

                4 -> {
                    code = 0
                }
            }
            map["code"] = code
            for (result in resultList.iterator()) {
                result.success(map)
            }
            resultList.clear();
            channel.invokeMethod("flutter_tenc_map_backLocation", map)

        }
    }

    override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
    }
}
